package com.zh.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.BaseResponse;
import com.zh.common.ErrorCode;
import com.zh.common.ResultUtils;
import com.zh.config.RedisKeyConfig;
import com.zh.domain.entity.LoginLog;
import com.zh.exception.ThrowUtils;
import com.zh.service.LoginLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "LogController", value = "日志控制器")
@RestController
@RequestMapping("/log")
@Slf4j
public class LogController {

    private final LoginLogService loginLogService;

    public LogController(LoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }

    @GetMapping("/login")
    @ApiOperation("登录日志查询")
    @SaCheckLogin
    public BaseResponse<List<LoginLog>> getLoginLog(Integer userId) {
        ThrowUtils.throwIf(userId == null, ErrorCode.PARAMS_ERROR, "用户id不能为空");
        LambdaQueryWrapper<LoginLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginLog::getLoginId, userId)
                .orderByDesc(LoginLog::getLoginTime)
                .last("LIMIT 20"); // 限制查询结果为最新的 20 条
        List<LoginLog> list = loginLogService.list(queryWrapper);
        return ResultUtils.success(list);
    }
}
